#ifdef MBM_IMIBASE_SUPPORT

#include "mbm_spreadtrum_inc.h"

#include "mbm_typedefine.h"
#include "mbm_png_adapter.h"
#include "mbm_memory_adapter.h"

#ifdef MBM_DEBUG_PNG
#define MBM_PNG_TRACE mbm_trace
#else
#define MBM_PNG_TRACE
#endif

uint8 *png_data_ptr = 0;
	
/**
 * @name mbm_png_decode_init -discripe
 *
 * @param param1	-property	-discripe
 *
 * @return -discripe
 */
void mbm_png_decode_init()
{
	SCI_ASSERT(png_data_ptr==0);
}

/**
 * @name mbm_png_decode_deinit -discripe
 *
 * @param param1	-property	-discripe
 *
 * @return -discripe
 */
void mbm_png_decode_deinit()
{
	if(png_data_ptr) 
	{
		MBM_Free(png_data_ptr);
		png_data_ptr = 0;
	}
}

/**
 * @name mbm_png_decode -discripe
 *
 * @param param1	-property	-discripe
 *
 * @return -discripe
 */
void mbm_png_decode( ImpCStr pngName, Int8 **img_p, Int32 *img_w, Int32 *img_h)
{
	uint16          wPngName[200] = {0};
	uint8 *data_ptr = 0;
	uint32 data_size = 0;
	
	SFS_HANDLE s_pngfile_handle = 0;
	uint32 file_size = 0;
	uint32 read_size = 0;
	uint8 *pReadFileBuff = NULL;
	uint16 w = 0;
	uint16 h = 0;

	MBM_PNG_TRACE("mbm_png_decode: %s", pngName);

	*img_p = 0;

	MMIAPICOM_StrToWstr(pngName,wPngName);    
	s_pngfile_handle = SFS_CreateFile(wPngName, SFS_MODE_READ|SFS_MODE_OPEN_EXISTING, NULL, NULL);
	SCI_ASSERT(0 != s_pngfile_handle);
	SCI_ASSERT(SFS_GetFileSize(s_pngfile_handle, &file_size) == SFS_NO_ERROR);
	pReadFileBuff = MBM_Malloc(file_size);
	SCI_ASSERT(0 != pReadFileBuff);
	SFS_ReadFile(s_pngfile_handle, pReadFileBuff, file_size, &read_size, 0);
	SCI_ASSERT(read_size == file_size);
	SCI_ASSERT(GUIANIM_GetImageTypeByData(pReadFileBuff) == GUIANIM_TYPE_IMAGE_PNG);
	GUIANIM_GetImageInfoByData(pReadFileBuff, &w, &h, file_size, GUIANIM_TYPE_IMAGE_PNG);
	MBM_Free(pReadFileBuff);
	SFS_CloseFile(s_pngfile_handle);

	MBM_PNG_TRACE("mbm_png_decode: size=%d, w=%d, h=%d", file_size, w, h);

	data_size = w * h * 2;
	data_ptr = MBM_Malloc(data_size);
	if(data_ptr)
	{
		if(GUIREF_AllocMemory(FALSE,TRUE,TRUE,TRUE))
		{
			GUIREF_CreatFile(wPngName);
			if(GUIREF_DecodePng(data_ptr, wPngName, data_size, w, h, img_w, img_h, PNULL, PNULL))
			{
				png_data_ptr = MBM_Malloc((*img_w) * (*img_h) * 3);
				if(png_data_ptr)
				{
					int32 x, y;
					for(y=0; y<(*img_h); y++)
					{
						uint16 *buf0 = ((uint16*)data_ptr) + y*(*img_w);
						uint8 *buf1 = png_data_ptr + y*(*img_w)*3;
						for(x=0; x<(*img_w); x++)
						{
							*buf1++ = (uint8)((buf0[x]>>8) & 0xf8);
							*buf1++ = (uint8)((buf0[x]>>3) & 0xfc);						
							*buf1++ = (uint8)((buf0[x]<<3) & 0xf8);
						}
					}
					*img_p = png_data_ptr;
				}
			}
		}
		MBM_Free(data_ptr);
	}

	MBM_PNG_TRACE("mbm_png_decode: %x, %d, %d, %d", *img_p, data_size, *img_w, *img_h);
}

#endif /* MBM_IMIBASE_SUPPORT */
